<!--登录-->
<template>
  <div class="login">
    <vue-particles
        class="login-bg"
        color="#39AFFD"
        :particleOpacity="0.7"
        :particlesNumber="20"
        shapeType="polygon"
        :particleSize="4"
        linesColor="#39AFFD"
        :linesWidth="1"
        :lineLinked="true"
        :lineOpacity="0.4"
        :linesDistance="150"
        :moveSpeed="3"
        :hoverEffect="true"
        hoverMode="grab"
        :clickEffect="true"
        clickMode="push"
    >
    </vue-particles>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">后台管理系统</h3>
      <el-form-item v-if="tenantEnabled" prop="tenantId">
        <el-select v-model="loginForm.tenantId" filterable placeholder="请选择公司" style="width: 100%">
          <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"></el-option>
          <svg-icon slot="prefix" icon-class="company" class="el-input__icon input-icon"/>
        </el-select>
      </el-form-item>
      <el-form-item prop="username">
        <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="账号"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
            class="input-item"
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 65%"
            @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
        </el-input>
        <div class="login-code">
          <img v-if="!loadingCode" :src="codeUrl" @click="getCode" class="login-code-img"/>
          <span v-else>获 取 中...</span>
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:12px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="float: right;">
        <el-button circle title="微信登录" @click="thirdLogin('wechat_open')">
          <svg-icon icon-class="wechat" />
        </el-button>
        <el-button circle title="Gitee登录" @click="thirdLogin('gitee')">
          <svg-icon icon-class="gitee" />
        </el-button>
        <el-button circle title="MaxKey登录" @click="thirdLogin('maxkey')">
          <svg-icon icon-class="maxkey" />
        </el-button>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
            class="btn-item"
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;"
            @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2023-2023 kcx All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg,getTenantList } from '@/api/login'
import { thirdBinding } from '@/api/system/thirdAuth';
import Cookies from 'js-cookie'
import { decrypt, encrypt } from '@/utils/jsencrypt'

export default {
  name: 'Login',
  components: {},
  data() {
    return {
      codeUrl: '' +
          'WHRTb2Z0d2FyZQBTbmlwYXN0ZV0Xzt0AAAAXdEVYdFVzZXIgQ29tbWVudABTY3JlZW5zaG9093UNRwAABJZJREFUaIHtmM2L4kgYxp9ZjY' +
          'rGcantjk2THgi2hxyEQMBLDv7tOeQiBAIe6qCSpTuENtNTrJ/EL3oPMRqjbWV3GYaF/E525U3Vm6fej6r+8vHxgZyb/ParHfgfkGvEJ9eIT6' +
          '4Rn1wjPrlGfHKN+OQa8ck14pNrxCfXiM/P0IgN+rbt/oSJfxFfeHdaz7Ymi8thoaF2nyUAQECdIb4ZKjk9dan5XTgaJAmoQ9lefNT12sgaTn' +
          'eH4QJpa53YeuzY3qaRfj0YWX+i3X2W4kk+81h81J/ClEGBkDJjq5RlkShnbn9CkWuR+gAgkgAAG/Tdzb3+lBz3T35Qy6ZAkShtvBw9LhKlZ0R' +
          'uPRuHOT3bek9O7i0LRWFKHU/S5MSq5GvJpRadG2pL1ZLujB37r4auK0mfIwPPtt5LKeeTb1X4AiGbRplRVDVMxJRLze9CWyWgL1d3LA7AxJBL' +
          'TX9N2lpH8mxrYtHq6S2JdCQyduw3yloZNh8A3PlCENVEeL6Vj26w1aZQqmWaJotGeza0zeH5mNC4aiqp2tyxLQqjMjF9yMazBAS3pw/CEOXfp' +
          'SiDEMesrBvVQd81+yyZdC1Nb2XwOGI8XRXrSjKGKsfACdhsW364Fl+X/JdcS8EGfZdtAQBL1wQAeJbtoUoIdsw1rUQZFxpq93m+3lcaBGAAVtT' +
          'x5iKpTVP7Ida21HIm7bvNMCqLVdlQWwCCkTXcPkS/rxKM3pbVB+0YceeBs9zuavWMcv+jXDsUIF1RewoANjl7Sjrd2KHzmh1QZxbl2tk4m2xidw' +
          'Whqaqd24tLcqRLRl/H/nR32CSg1uxp2GxRip8G4bpYbmacKptGy5FlxT3It00fQFU2sq5xg4VvRxFH+yPE2sU7kSFYkvP4AOKG61JvefgN6tB1Z' +
          'JUqGq5pueJjqthfIXscVWWjuYq8r13fz1RLPva1h/Ue5UvzVNydoq9Zf6FTD5CDH4td7S5LRqQ+dTxdibXqYpM0kXVDPn/Js63zTPiELBqVqz' +
          'XMMthJx5Z8nmtjx61c77LR4atASBkAlLrov08CdCplOg8DsMl8L97Ll6+N6aj+xy1PWpr+SdH8N/A0CsJQEOrAW6bZ2KDvslKz1wCwfe3br/e' +
          '6rlzvsgF1KCvLhq4DcKk5B1AtCfvZDwa1LvrvExezbfXhIhFW1GHrux7CYfrJDcJB32bnoS8+NoFM7Z+jUfBjsSvdSdcdOiRLQKM/Y4E0GS4Fh' +
          'KeuMuk7g7DMcDqkHJES58AgXKNUl0BQf2HrVZQXAXVm5NtZoi23O6zYutnTZAQj/sedqHS6zxffNrJwquI34GgUR3vCoSk1/RWERj0emB/KTa' +
          'K+HCCdLgZ9V7zXbx9E5utDFUsI570yfG2fTRiEa9SaPe1K9l1nO6WWDQBXg2W53aFczXBE4mg0Q6OtIL43sAGAhtrTIpePF64CeUxUX38FoEg' +
          'UCYA7YaVm77PGcbq7FEgbtmWnL4ZRG4rvhgcFT+vGrR3AMu5rwEnHdF9LLYoiUbI0BO6dNif//1EGco345BrxyTXik2vEJ9eIT64Rn1wjPrlGf' +
          'HKN+OQa8fkb2tdL+z51kuUAAAAASUVORK5CYII=',
      loginForm: {
        tenantId: '000000',
        username: 'admin',
        password: '123456',
        rememberMe: false,
        code: '',
        uuid: ''
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', message: '请输入您的账号' }
        ],
        password: [
          { required: true, trigger: 'blur', message: '请输入您的密码' }
        ],
        code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
      },
      loading: false,
      loadingCode: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: true,
      redirect: undefined,
      tenantEnabled:true,
      tenantList:[],
    }
  },
  watch: {
    //$route对象是vue中的一个包含当前路由信息的对象，它通常用于获取URL中的参数、查询字符串等信息
    $route: {
      handler: function(route) {
        //监听路由之前的地址，以便在登录后重定向到输入的地址
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.initTenantList()
    this.getCode()
    this.getCookie()
  },
  methods: {
    /**
     * 获取租户列表
     * @returns {Promise<void>}
     */
    async initTenantList() {
      await getTenantList(false).then(res => {
        this.tenantEnabled = res.data.tenantEnabled === undefined ? true : res.data.tenantEnabled;
        if (this.tenantEnabled) {
          this.tenantList = res.data.voList;
          if (this.tenantList != null && this.tenantList.length !== 0) {
            this.loginForm.tenantId = this.tenantList[0].tenantId;
          }
        }
      })
    },
    /**
     * 获取验证码
     */
    getCode() {
      this.loadingCode=true
      getCodeImg().then(res => {
        this.captchaEnabled = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.data.img
          this.loginForm.uuid = res.data.uuid
        }
      }).finally(() => {
        this.loadingCode=false
      });
    },
    /**
     * 获取缓存的账号密码
     */
    getCookie() {
      const tenantId = Cookies.get('tenantId')
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        tenantId: tenantId === undefined ? this.loginForm.tenantId : tenantId,
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
    /**
     * 登录
     */
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.loginForm.rememberMe) {
            Cookies.set('tenantId', this.loginForm.tenantId, { expires: 30 })
            Cookies.set('username', this.loginForm.username, { expires: 30 })
            Cookies.set('password', encrypt(this.loginForm.password), { expires: 30 })
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
          } else {
            Cookies.remove('tenantId')
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
          }
          this.$store.dispatch('user/Login', this.loginForm).then(() => {
            //跳转到之前未登录输入的页面或进入首页
            this.$router.push({ path: this.redirect || '/' }).catch(() => {
            })
          }).catch(() => {
            this.loading = false
            if (this.captchaEnabled) {
              this.getCode()
            }
          })
        }
      })
    },
    /**
     * 第三方登录
     * @param type
     */
    thirdLogin(type){
      thirdBinding(type, this.loginForm.tenantId).then((res => {
        window.location.href = res.data;
      }))
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.login-bg {
  width: 100%;
  height: calc(100% - 100px);
  position: absolute;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}
/*登录表单样式*/
.login-form {
  position: relative;
  border-radius: 6px;
 // background: #ffffff;
  background-image: linear-gradient(to bottom right,rgb(225, 230, 237), rgb(255, 255, 255));
  width: 400px;
  padding: 25px 25px 5px 25px;
  ::v-deep .el-input {
    height: 38px;
    input {
      height: 38px;
      box-sizing: border-box;
      box-shadow: inset 2px 2px 5px #babecc, inset -2px -2px 15px #ffffff;
      transition: all 0.2s ease-in-out;
    }
    input:focus {
      box-shadow: inset 1px 1px 2px #babecc, inset -1px -1px 2px #ffffff;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
  .el-button {
    box-shadow: 5px 5px 10px #babecc, -5px -5px 20px #ffffff;
    transition: all 0.2s ease-in-out;
  }
  .el-button:hover {
    box-shadow: 2px 2px 5px #babecc, -2px -2px 5px #ffffff;
  }
}

.login-code {
  width: 30%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.login-code-img {
  height: 100%;
  width: 100%;
  object-fit: contain;
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>
